<?php

namespace App\Services\SeckillInstall;

use Carbon\Carbon;
use App\Models\User;
use App\Models\SeckillProduct;
use App\Jobs\RewardFirstParentJob;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Collection;

class RefreshSeckillProducts
{
	
	public function tree($data,$price,$result){


		foreach($data as $k=>$v){

		 	if($v['stock'] > 0  && $price >= $v['price_vip']){

		 		if($v['is_new']){
		 			$result[$k]['id'] = $v['id'];
					$result[$k]['seckill_count'] = $v['stock'];
					$result[$k]['seckill_count_all'] = $v['stock'];
					$result[$k]['unallowed_area'] = $v['unallowed_area'];
					unset($data[$k]);
				}else{
					if(isset($result[$k])){
			 			$result[$k]['seckill_count'] +=1;
			 			$result[$k]['seckill_count_all'] +=1;

			 		}else{
			 			$result[$k]['id'] = $v['id'];
			 			$result[$k]['seckill_count'] = 1;
			 			$result[$k]['unallowed_area'] = $v['unallowed_area'];
			 			$result[$k]['seckill_count_all'] = 1;
			 		}

			 		$data[$k]['stock'] -= 1;
			 		$price -= $data[$k]['price_vip'];
			 		if($data[$k]['stock'] <= 0 ){

			 			unset($data[$k]);
			 		}

				}
		 		
		 	}

		 }
		 
		 if($price > 0 && !empty($data)){
		 	$minPrice = min(array_column($data,'price_vip'));
	 	 	$price = $price < $minPrice ? $minPrice : $price;
	 		$result = $this->tree($data, $price, $result);

		 }
		 return $result;

	}

    public function execute()
    {
     	 $products = SeckillProduct::query()->with(['product' => function($query){
		    	$query->join('product_skus', 'product_skus.product_id', '=', 'products.id')
		    		->where('product_skus.stock','>',0);
		    }])
   		 ->where('is_open',true)
		 ->get();


		 $data = [];

		 if($products){
		 	foreach($products as $k=>$v){
		 		if($v->product){
					$data[$k] = [
			 			'id' => $v->id,
			 			'price_vip' => $v->product->price_vip,
			 			'stock' => $v->product->stock,
			 			'is_new' => $v->is_new,
			 			'unallowed_area' => $v->product->unallowed_area,
			 		];
		 		}
		 	}
		 	 $sort = array_column($data,'price_vip');
			 array_multisort($sort,SORT_DESC,$data);
		 }
		
		 $goodsTotalPrice = cs('good')->goods_total_price;

		 if(empty($data)){

		 	return false;
		 }
		 $finalResult = $this->tree($data, $goodsTotalPrice, []);

		 if($finalResult){
		 	$finalResult = array_merge($finalResult);
		 	
		 	SeckillProduct::query()->where('id','>','0')->update(['seckill_count'=>0,'unallowed_area'=>'']);
		 	$update = SeckillProduct::updateBatch($finalResult);
		 	
		 }
    }

	public function __invoke()
	{
		//Dinglog::text("========== refresh seckill product num start ......");

		$this->execute();

		//Dinglog::text("========== refresh seckill product num end ......");
	}
}
